<!--
 * @Description:共享书籍
 * @Author: zhangweigang
 * @Date: 2021-03-20 21:44:06
 * @LastEditTime: 2021-05-05 10:29:22
 * @LastEditors: zhangweigang
-->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }"><span class="tW">首页</span></el-breadcrumb-item>
      <el-breadcrumb-item><span class="tW">书籍管理</span></el-breadcrumb-item>
      <el-breadcrumb-item><span class="tW">共享书籍</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <!--  :span 指定宽度 -->
        <el-col :span="5">
          <el-input placeholder="请输入书籍名称" v-model="bookName" clearable @clear="contentClear">
            <el-button slot="append" @click="onSubmit" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-table class="pag" :data="listData" stripe border>
        <el-table-column label="书籍名称" header-align="center">
          <template slot-scope="scope">
            <!-- 查看按钮  -->
            <a :href="scope.row.bookUrl" target="_black" class="a-text">{{ scope.row.name }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" header-align="center"></el-table-column>
        <el-table-column prop="categoryName" label="书籍分类" header-align="center"></el-table-column>
        <el-table-column prop="publicationDate" width="180" label="出版时间" header-align="center"></el-table-column>
        <el-table-column prop="createDate" width="180" label="上传时间" header-align="center"></el-table-column>
        <el-table-column label="是否共享" width="120" header-align="center">
          <template slot-scope="scope">
            <!-- 1:共享书籍 2:非共享书籍 -->
            <el-tag type="success" v-if="scope.row.isShare == 1">已共享</el-tag>
            <el-tag type="danger" v-else>未共享</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否审核" width="120" header-align="center">
          <template slot-scope="scope">
            <!-- 审核标识 1:已审核 2:未审核 3:审核不通过 -->
            <el-tag type="success" v-if="scope.row.isAudit == 1">已审核</el-tag>
            <el-tag type="danger" v-else>未审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" header-align="center">
          <template slot-scope="scope">
            <!-- 修改  -->
            <el-button type="success" size="mini" @click="showModifyBookList(scope.row)">修改</el-button>
            <!-- 删除 -->
            <el-button type="danger" size="mini" @click="removeByIdBook(scope.row.id)">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 书籍分页 -->
      <div class="pag">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 修改信息 -->
    <el-dialog title="修改书籍信息" :visible.sync="modifyBookDialogVisible" @close="reviewDialogClosed" width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="modifyBookForm" :rules="modifyBookRules" ref="modifyBookRef" label-width="100px">
        <el-form-item label="书籍名称" prop="name">
          <el-input v-model="modifyBookForm.name"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="modifyBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="书籍类型" prop="bookCategoryId">
          <el-select v-model="modifyBookForm.bookCategoryId" placeholder="请选择书籍类型" @change="bookSelectCate">
            <el-option v-for="(item, index) in bookCateList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出版日期" prop="publicationDate">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="modifyBookForm.publicationDate" style="width: 100%"></el-date-picker>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyBookDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBookInfo">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bookShareManagerInfoAipService from '@/network/aipBookShareService.js'
export default {
  data() {
    return {
      modifyBookDialogVisible: false,
      currentPage: 1,
      total: 0,
      // 默认分页参数
      pageNum: 1, // 当前页数
      pageSize: 10, // 每页显示多少条数据
      bookName: '', // 搜索关键字
      listData: [], // 书籍列表
      bookCateList: [], // 书籍分类列表
      tempBook: null,
      modifyBookForm: {
        name: '',
        author: '',
        bookCategoryId: '',
        publicationDate: '',
        categoryName: ''
      },
      modifyBookRules: {
        name: [
          { required: true, message: '请输入书籍名称', trigger: 'blur' },
          {
            min: 1,
            max: 120,
            message: '长度在 1 到 120 个字符',
            trigger: 'blur'
          }
        ],
        author: [
          { required: true, message: '请输入作者名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ],
        bookCategoryId: [{ required: true, message: '请选择书籍类型', trigger: 'change' }],
        publicationDate: [
          {
            type: 'date',
            required: true,
            message: '请选择书籍出版日期',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.getAllCateData()
    // 书籍分页
    this.getPageData(this.pageNum, this.pageSize, 1)
  },
  methods: {
    // 获取分类
    getAllCateData() {
      bookShareManagerInfoAipService.getBookCateInfo().then(res => {
        if (res.data.code === 0 && res.status === 200) {
          res.data.data.map(item => {
            this.bookCateList.push(item)
          })
        } else {
          this.$message({
            showClose: true,
            message: '书籍分类获取失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    // 监听 pagesize 改变事件
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getPageData(this.pageNum, pageSize, 1)
    },
    // 监听 页码值 改变事件
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.getPageData(pageNum, this.pageSize, 1)
    },
    /**
     * 非共享书籍分页数据
     * @pageNum 当前页数
     * @pageSize 每页显示多少条数据
     */
    getPageData(pageNum, pageSize, isShare) {
      let params = {
        isShare: isShare
      }
      bookShareManagerInfoAipService.getNoBookPagination(pageNum, pageSize, params).then(res => {
        if (res.data.code === 0) {
          console.log(res, '所有非共享书籍')
          this.total = res.data.total
          // 获取留言列表
          this.listData = res.data.rows
        } else {
          this.$message({
            showClose: true,
            message: '获取失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
          return
        }
      })
    },
    contentClear() {
      this.getPageData(this.pageNum, this.pageSize, 1)
    },
    // 查询书籍
    onSubmit() {
      let params = {
        name: this.bookName
      }
      bookShareManagerInfoAipService.getBookByName(params).then(res => {
        if (res.data.code === 0) {
          this.total = res.data.total
          this.listData = res.data.rows
          this.$message.success('查询成功！')
        }
      })
    },
    reviewDialogClosed() {
      this.$refs.modifyBookRef.resetFields()
    },
    // select改变时触发
    bookSelectCate(id) {
      this.modifyBookForm.bookCategoryId = id
      bookShareManagerInfoAipService.getCateNameById(id).then(res => {
        console.log(res, '分类名称')
        if (res.data.code === 0) {
          this.modifyBookForm.categoryName = res.data.data.name
        }
      })
      console.log(this.modifyBookForm, '分类参数')
    },
    // 修改书籍
    showModifyBookList(scope) {
      this.tempBook = {
        auditContent: scope.auditContent,
        bookUrl: scope.bookUrl,
        content: scope.content,
        copyrightUrl: scope.copyrightUrl,
        coverUrl: scope.coverUrl,
        createDate: scope.createDate,
        creator: scope.creator,
        delFlag: scope.delFlag,
        fileId: scope.fileId,
        id: scope.id,
        isAudit: scope.isAudit,
        isShare: scope.isShare,
        updateDate: scope.updateDate,
        updater: localStorage.getItem('adminname'),
        uploadDate: scope.uploadUserId,
        uploadUserId: scope.uploadUserId
      }
      this.modifyBookForm = {
        name: scope.name,
        author: scope.author,
        publicationDate: scope.publicationDate
      }
      this.modifyBookDialogVisible = true
    },
    // 删除书籍
    async removeByIdBook(id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果点击确定 返回为 confirm，点击取消 返回为 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      }
      bookShareManagerInfoAipService.removeBookById(id).then(res => {
        if (res.data.code === 0) {
          this.$message({
            showClose: true,
            message: '删除成功！',
            type: 'error',
            duration: 4000
          })
          this.getPageData(this.pageNum, this.pageSize, 1)
        } else {
          this.$message({
            showClose: true,
            message: '删除失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    // 保存修改的书籍
    saveBookInfo() {
      let time = this.getYMD(this.modifyBookForm.publicationDate)
      let params = {
        ...this.tempBook,
        name: this.modifyBookForm.name,
        author: this.modifyBookForm.author,
        bookCategoryId: this.modifyBookForm.bookCategoryId,
        publicationDate: time,
        categoryName: this.modifyBookForm.categoryName
      }
      console.log(params, '修改参数')
      bookShareManagerInfoAipService.modifyBookInfo(params).then(res => {
        if (res.data.code === 0) {
          console.log(res, '修改成功')
          this.$message({
            showClose: true,
            message: '修改书籍信息成功！',
            type: 'success',
            duration: 4000
          })
          this.getPageData(this.pageNum, this.pageSize, 1)
          this.modifyBookDialogVisible = false
        } else {
          this.$message({
            showClose: true,
            message: '修改失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
          this.modifyBookDialogVisible = false
        }
      })
    },
    /**
     * 获取时间
     * @time 中国标准时间
     * @return 返回时间 格式 年-月-日 小时:分钟:毫秒
     */
    getYMD(time) {
      console.log(time)
      let date = new Date(time)
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let M = date.getMinutes()
      M = M < 10 ? '0' + M : M
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      let dateTime = y + '-' + m + '-' + d + ' ' + h + ':' + M + ':' + s
      return dateTime
    }
  }
}
</script>

<style lang="less" scoped>
.pag {
  margin-top: 20px;
}
.a-text {
  text-decoration: underline;
  color: red;
}
</style>
